package cn._2dland.net
{
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;

	/**
	 * 网络连接工厂类 
	 * @author deadblue
	 * 
	 */	
	public class NetConnectionFactory
	{
		private static var _instance:NetConnectionFactory = new NetConnectionFactory();
		private var _nc:NetConnection = null;

		public function NetConnectionFactory() {
			_nc = new NetConnection();
			_nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			_nc.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_nc.connect(null);
		}

		public static function getInstance():NetConnectionFactory {
			return _instance;
		}

		public function getNetConnection():NetConnection {
			return _nc;
		}

		protected function netStatusHandler(e:NetStatusEvent):void {
			switch(e.info.code){
				case "NetConnection.Connect.Success":
					break;
				default:
					removeHandlers();
					_nc = null;
					break;
			}
		}

		protected function ioErrorHandler(e:IOErrorEvent):void {
			trace("connection io error!");
			removeHandlers();
			try {
				_nc.close();
			}
			catch(err:Error){}
			_nc = null;
		}

		private function removeHandlers():void {
			if(_nc == null) return;
			_nc.removeEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
			_nc.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}

	}
}